export const useTagsViewStore = defineStore('tagsView', () => {
	const visitedViews = ref(JSON.parse(localStorage.getItem('visitedViews')) || [])
	const cachedViews = ref(JSON.parse(localStorage.getItem('cachedViews')) || []);
	const iframeViews = ref(JSON.parse(localStorage.getItem('iframeViews')) || [])

	const saveToLocalStorage = () => {
		// 去除 matched 属性
		const removeMatched = (views) => {
			return views.map(view => {
				// 去除 matched 属性
				const { matched, ...rest } = view;
				return rest; // 只返回去除 matched 的其他部分
			});
		};
		// 使用 `.value` 获取实际值，并去除 matched 属性
		const rawVisitedViews = toRaw(visitedViews.value);
		const rawCachedViews = toRaw(cachedViews.value);
		const rawIframeViews = toRaw(iframeViews.value);
		const simplifiedVisitedViews = removeMatched(rawVisitedViews);
		const simplifiedIframeViews = removeMatched(rawIframeViews);
		// 保存到 localStorage
		localStorage.setItem('visitedViews', JSON.stringify(simplifiedVisitedViews));
		localStorage.setItem('cachedViews', JSON.stringify(rawCachedViews));
		localStorage.setItem('iframeViews', JSON.stringify(simplifiedIframeViews));
	};
	const removeToLocalStorage = () => {
		localStorage.removeItem('visitedViews');
		localStorage.removeItem('cachedViews');
		localStorage.removeItem('iframeViews');
	};

	const getVisitedViews = () => {
		return visitedViews.value
	};
	const getIframeViews = () => {
		return iframeViews.value
	};
	const getCachedViews = () => {
		return cachedViews.value;
	};
	const setVisitedViews = (val) => {
		visitedViews.value = val
	}


	const addView = (view) => {
		const cleanRoute = {
			name: view.name,
			path: view.path,
			fullPath: view.fullPath,
			query: { ...view.query },
			params: { ...view.params },
			meta: { ...view.meta }
		}
		addVisitedView(cleanRoute);
		addCachedView(cleanRoute);
		saveToLocalStorage();
	};
	const delView = (
		view
	) => {
		return new Promise((resolve) => {
			delVisitedView(view);
			if (!isDynamicRoute(view)) {
				delCachedView(view);
			}
			saveToLocalStorage();
			resolve({
				visitedViews: [...visitedViews.value],
				cachedViews: [...cachedViews.value]
			});
		});
	};

	const addIframeView = (view) => {
		if (iframeViews.value.some((v) => v.fullPath === view.fullPath)) return;
		iframeViews.value.push(
			Object.assign({}, view, {
				title: view.meta?.title || 'no-name'
			})
		);
		saveToLocalStorage();
	};
	const delIframeView = (view) => {
		return new Promise((resolve) => {
			iframeViews.value = iframeViews.value.filter((item) => item.fullPath !== view.fullPath);
			saveToLocalStorage();
			resolve([...iframeViews.value]);
		});
	};
	const addVisitedView = (view) => {
		if (visitedViews.value.some((v) => v.fullPath === view.fullPath)) {
			// console.log('相同路由');
			if (view.query && view.query.metaTitle) {
				const list = visitedViews.value.filter(
					(v) => v.query && v.query.metaTitle && v.query.metaTitle === view.query.metaTitle
				);
				if (list.length > 0) {
					return;
				}
			} else {
				return;
			}
		}
		if (visitedViews.value.some((v) => v.path === view.meta.activeMenu)) {
			// console.log('上级路由', view.meta.activeMenu);
			let i = visitedViews.value.findIndex((v) => v.path === view.meta.activeMenu);
			visitedViews.value.splice(i + 1, 0,
				Object.assign({}, view, {
					title: view.query && view.query.metaTitle ? view.query.metaTitle : view.meta?.title || 'no-name'
				})
			);
			return;
		}
		// console.log('不同的路由');
		visitedViews.value.push(
			Object.assign({}, view, {
				title: view.query && view.query.metaTitle ? view.query.metaTitle : view.meta?.title || 'no-name'
			})
		);
	};


	const delVisitedView = (view) => {
		return new Promise((resolve) => {
			for (const [i, v] of visitedViews.value.entries()) {
				if (v.fullPath === view.fullPath) {
					visitedViews.value.splice(i, 1);
					break;
				}
			}
			saveToLocalStorage();
			resolve([...visitedViews.value]);
		});
	};
	// const delCachedView = (view?)<string[]> => {
	// 	let viewName = '';
	// 	if (view) {
	// 		viewName = view.name as string;
	// 	}
	// 	return new Promise((resolve) => {
	// 		const index = cachedViews.value.indexOf(viewName);
	// 		index > -1 && cachedViews.value.splice(index, 1);
	// 		resolve([...cachedViews.value]);
	// 	});
	// };
	const delCachedView = (view) => {
		let viewName = '';
		if (view) {
			viewName = view.name;
		}
		return new Promise((resolve) => {
			// 判断该 name 在 visitedViews 中是否只出现一次
			const sameNameCount = visitedViews.value.filter(v => v.name === viewName).length;
			if (sameNameCount <= 1) {
				// 只存在一个时才从缓存中移除
				const index = cachedViews.value.indexOf(viewName);
				if (index > -1) {
					cachedViews.value.splice(index, 1);
				}
			}
			resolve([...cachedViews.value]);
		});
	};
	const delOthersViews = (
		view
	) => {
		return new Promise((resolve) => {
			delOthersVisitedViews(view);
			delOthersCachedViews(view);
			resolve({
				visitedViews: [...visitedViews.value],
				cachedViews: [...cachedViews.value]
			});
		});
	};

	const delOthersVisitedViews = (view) => {
		return new Promise((resolve) => {
			visitedViews.value = visitedViews.value.filter((v) => {
				return v.meta?.affix || v.fullPath === view.fullPath;
			});
			resolve([...visitedViews.value]);
		});
	};
	const delOthersCachedViews = (view) => {
		const viewName = view.name
		return new Promise((resolve) => {
			const index = cachedViews.value.indexOf(viewName);
			if (index > -1) {
				cachedViews.value = cachedViews.value.slice(index, index + 1);
			} else {
				cachedViews.value = [];
			}
			resolve([...cachedViews.value]);
		});
	};

	const delAllViews = () => {
		return new Promise((resolve) => {
			delAllVisitedViews();
			delAllCachedViews();
			resolve({
				visitedViews: [...visitedViews.value],
				cachedViews: [...cachedViews.value]
			});
		});
	};
	const delAllVisitedViews = () => {
		return new Promise((resolve) => {
			visitedViews.value = visitedViews.value.filter((tag) => tag.meta?.affix);
			saveToLocalStorage();
			resolve([...visitedViews.value]);
		});
	};

	const delAllCachedViews = () => {
		return new Promise((resolve) => {
			cachedViews.value = [];
			resolve([...cachedViews.value]);
		});
	};

	const updateVisitedView = (view) => {
		console.log(44);
		for (let v of visitedViews.value) {
			if (v.fullPath === view.fullPath) {
				v = Object.assign(v, view);
				break;
			}
		}
	};
	const delRightTags = (view) => {
		return new Promise((resolve) => {
			const index = visitedViews.value.findIndex((v) => v.fullPath === view.fullPath);
			if (index === -1) {
				return;
			}
			visitedViews.value = visitedViews.value.filter((item, idx) => {
				if (idx <= index || (item.meta && item.meta.affix)) {
					return true;
				}
				const i = cachedViews.value.indexOf(item.name);
				if (i > -1) {
					cachedViews.value.splice(i, 1);
				}
				return false;
			});
			saveToLocalStorage();
			resolve([...visitedViews.value]);
		});
	};
	const delLeftTags = (view) => {
		return new Promise((resolve) => {
			const index = visitedViews.value.findIndex((v) => v.fullPath === view.fullPath);
			if (index === -1) {
				return;
			}
			visitedViews.value = visitedViews.value.filter((item, idx) => {
				if (idx >= index || (item.meta && item.meta.affix)) {
					return true;
				}
				const i = cachedViews.value.indexOf(item.name);
				if (i > -1) {
					cachedViews.value.splice(i, 1);
				}
				return false;
			});
			resolve([...visitedViews.value]);
		});
	};

	const addCachedView = (view) => {
		const viewName = view.name;
		if (!viewName) return;
		if (cachedViews.value.includes(viewName)) return;
		if (!view.meta?.noCache) {
			cachedViews.value.push(viewName);
		}
	};

	const isDynamicRoute = (view) => {
		// 检查匹配的路由记录中是否有动态段
		return view.matched && view.matched.some((m) => m.path.includes(':'));
	};


	return {
		visitedViews,
		cachedViews,
		iframeViews,

		getVisitedViews,
		getIframeViews,
		getCachedViews,
		setVisitedViews,

		addVisitedView,
		addCachedView,
		delVisitedView,
		delCachedView,
		updateVisitedView,
		addView,
		delView,
		delAllViews,
		delAllVisitedViews,
		delAllCachedViews,
		delOthersViews,
		delRightTags,
		delLeftTags,
		addIframeView,
		delIframeView,
		removeToLocalStorage
	};
});
export default useTagsViewStore;
